package service

import (
	"context"
	"github.com/go-kratos/kratos/v2/errors"
	"go-mall/app/usercenter-svc/internal/dao"
	"go-mall/app/usercenter-svc/internal/model"
	"go-mall/libs/middleware"
	"go-mall/libs/response"
	"time"

	pb "go-mall/api/usercenter/v1"
)

const (
	errID = "userCenter"
)

type UserService struct {
	pb.UnimplementedUserServer
	dao *dao.Dao
}

func NewUserService() *UserService {
	return &UserService{
		dao: dao.New(),
	}
}

func (s *UserService) Register(ctx context.Context, req *pb.RegisterUserRequest) (*pb.RegisterUserReply, error) {
	user := s.dao.GetUserByUserName(req.UserName)
	if user != nil {
		return nil, response.NewDataNotFound(errID, "用户已存在！")
	}
	newUser := &model.MallUsers{
		NickName:    req.NickName,
		UserName:    req.UserName,
		Password:    req.Password,
		Avatar:      req.Avatar,
		CreatedTime: time.Now(),
		UpdatedTime: time.Now(),
	}
	if err := s.dao.CreateUser(newUser); err != nil {
		fe := errors.FromError(err)
		return nil, response.NewDataNotFound(errID, "保持用户失败！"+fe.Message)
	}
	return &pb.RegisterUserReply{UserId: int64(newUser.ID)}, nil
}
func (s *UserService) Login(ctx context.Context, req *pb.LoginUserRequest) (*pb.LoginUserReply, error) {
	user := s.dao.GetUserByUserNameAndPassword(req.UserName, req.Password)
	if user != nil {
		resp := &pb.LoginUserReply{}
		jwtToken, _ := middleware.GenerateToken(user.ID, user.UserName, user.Avatar, "userCenter")
		resp.UserName = user.UserName
		resp.Avatar = user.Avatar
		resp.NickName = user.NickName
		resp.JwtToken = jwtToken
		resp.UserId = int64(user.ID)
		return resp, nil
	}
	return nil, nil
}
